/* eslint-disable no-case-declarations */
import TauPage from '@/components/TauPage';
import TauActionPanel from '@/components/TauActionPanel';
import TauTable from '@/components/TauTable';
import { useStore } from '@/hooks';
import { Dialog, Drawer, Message, Button, Checkbox, Tab } from '@alifd/next';
import { t } from '@lingui/macro';
import { uniqueId } from 'lodash';
import { observer } from 'mobx-react-lite';
import React, { useRef, useState, useEffect } from 'react';
import { ENUMS, column, toSelectDataSource } from './stores/definitions';
import MoreFuncDropDown from '@/components/MoreFuncDropDown';
import { toJS } from 'mobx';

import ViewActives from './components/ViewActives';
import ComponentsDrawer from '@/components/Drawers/ComponentsDrawer';
import CommandCode from './components/CommandCode';

const tableId = uniqueId('tauTable-');

const tabDataSource = [
  { key: 'all', title: t`全部` },
  { key: 'partner', title: t`合伙人` },
  { key: 'merchant', title: t`渠道商户` },
  // { key: 'official', title: t`公众号` },
  { key: 'driver', title: t`司机` },
  { key: 'company', title: t`公司` },
  { key: 'activity', title: t`活动` },
];

function Coupon() {
  const [modal, setModal] = useState([]);
  const { sceneStore: store } = useStore();
  const objRef = useRef(); // 当前选中的对
  const [userInfo, setUserInfo] = useState({
    id: '',
    name: '',
  });
  const [code, setCode] = useState('');


  useEffect(() => {
    return () => {
      store._tabState = 'partner';
    };
  }, []);

  // 获取列表数据
  const handleOnSearch = (params) => {
    const { upDate, activeType, ...searchArgs } = params.values;
    const [from, to] = upDate || [];
    store.search = {
      from,
      to,
      activeType,
      ...searchArgs,
    };
  };

  // // 点击打开编辑
  const handleOpenActives = (current, type) => {
    objRef.current = { ...current, activeType: type };
    setModal(['actives']);
  };

  // // Modal窗口关闭回调
  const handleCancel = () => {
    setModal([]);
  };

  // 删除活动
  const handleRemoveActivity = (record) => {
    Dialog.confirm({
      title: t`删除场景`,
      content: t`确认要删除该场景吗? 一但删除, 无法撤回!`,
      onOk: async () => {
        try {
          await store.remove(record);
          Message.success({ content: t`场景删除成功` });
        } catch (error) {
          Message.error({ content: t`场景删除失败`, duration: 7000 });
          throw error;
        }
      },
    });
  };

  // 查看详情
  const handleOpenView = async (result) => {
    const { inviteCode, promoterName } = result;
    switch (store._tabState) {
      case 'partner':
        const partner = await store.api.getInviteCode(inviteCode);
        setUserInfo({
          id: partner?.username,
          name: partner?.fullname,
        });
        setModal(['partnerForm']);
        return;
      case 'merchant':
        const merchant = await store.api.getInviteCode(inviteCode);
        const channel = await store.api.getMerchants(merchant?.accountId);
        setUserInfo({
          id: channel?.associatedChannel,
          name: channel?.name,
        });
        setModal(['channelForm']);
        return;
      case 'official':
        const official = await store.api.getInviteCode(inviteCode);
        const officialInfo = await store.api.getMerchants(official?.accountId);
        setUserInfo({
          id: officialInfo?.associatedChannel,
          name: officialInfo?.name,
        });
        setModal(['channelForm']);
        return;
      case 'driver':
        const driver = await store.api.getInviteCode(inviteCode);
        setUserInfo({
          id: driver?.username,
          name: driver?.fullname,
        });
        setModal(['driverForm']);
        return;
      case 'company':
        const company = await store.api.getInviteCode(inviteCode);
        setUserInfo({
          id: company?.accountId,
          name: company?.fullname,
        });
        setModal(['companyForm']);
        return;
      case 'activity':
        setUserInfo({
          id: inviteCode,
          name: promoterName,
        });
        setModal(['activityForm']);
        return;
      default:
        break;
    }
    objRef.current = result;
    setModal(['view']);
  };

  return (
    <TauPage className="page-container">
      <TauActionPanel
        onSearch={handleOnSearch}
        searchItems={[
          {
            name: 'subSceneType',
            type: 'select',
            props: {
              dataSource: toSelectDataSource(ENUMS.subSceneType),
              placeholder: t`场景类型`,
              style: { width: 160 },
            },
          },
          {
            name: 'activeType',
            type: 'select',
            props: {
              dataSource: toSelectDataSource(ENUMS.activeType),
              placeholder: t`活动行为类型`,
              style: { width: 160 },
            },
          },
          // {
          //   name: 'upDate',
          //   type: 'date-range',
          //   props: {
          //     placeholder: [t`开始创建时间`, t`结束创建时间`],
          //   },
          // },
        ]}
        keywordSearch={{
          // enabled: true,
          placeholder: t`请输入关键字搜索`,
        }}
        className="action-panel"
      />
      <div className="content">
        <Tab
          activeKey={store.tabStatus}
          onChange={(e) => {
            store.tabStatus = e;
          }}
        >
          {tabDataSource.map(({ title, key }) => <Tab.Item title={title} key={key} />)}
        </Tab>
        <TauTable
          instanceId={tableId}
          primaryKey="id"
          tableLayout="fixed"
          currentPage={store.pg.page}
          pageSize={store.pg.size}
          total={store.total}
          sort={store.tableSort}
          onFetch={(pg) => { store.pg = pg; }}
          loading={store.loading}
          dataSource={toJS(store.data)}
          columns={[
            { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
            column('scene', {
              width: 100,
              cell: (v, _, activity) => <Button text type="primary" onClick={() => handleOpenView(activity)}>{v}</Button>,
            }),
            column('sceneName', {
              width: 148,
            }),
            column('click', {
              width: 68,
              sortable: true,
            }),
            column('register', {
              width: 68,
              cell: (v, _, activity) => <Button type="primary" text onClick={() => handleOpenActives(activity, 'REGISTER')}>{v}</Button>,
              sortable: true,
            }),
            column('order', {
              width: 68,
              cell: (v, _, activity) => <Button type="primary" text onClick={() => handleOpenActives(activity, 'ORDER')}>{v}</Button>,
              sortable: true,
            }),
            column('code', {
              width: 100,
            }),
            column('inviteCode', {
              width: 148,
            }),
            column('promoterName', {
              width: 148,
              cell: (v, _, activity) => <Button type="primary" text onClick={() => handleOpenView(activity)}>{v}</Button>,
            }),
            // {
            //   title: t`操作`,
            //   dataIndex: 'sceneNumber',
            //   width: 138,
            //   cell: (_, i, coupon) => {
            //     const funcMenu = [
            //       {
            //         title: '图表统计',
            //         onClick: () => handleOpenDetail(coupon),
            //         show: true,
            //       },
            //       {
            //         title: '删除',
            //         onClick: () => handleRemoveActivity(coupon),
            //         color: 'red',
            //         show: true,
            //       },
            //     ];
            //     return (
            //       <MoreFuncDropDown
            //         dropdownItems={funcMenu}
            //         maxShow={2}
            //       />
            //     );
            //   },
            // },
          ]}
        />
      </div>
      <ViewActives data={objRef.current} modal={modal} onCancel={handleCancel} />
      <ComponentsDrawer modal={modal} queryParams={{ id: userInfo.id }} name={userInfo.name} onCancel={() => handleCancel()} />

      <CommandCode modal={modal} activityInfo={objRef.current} commandCode={code} onCancel={() => setModal([])} />
    </TauPage>
  );
}

export default observer(Coupon);
